<template>
  <div class="search-box-container">
    <div class="search-box">
      <el-autocomplete
        v-model="inputData"
        :fetch-suggestions="querySearch"
        popper-class="my-autocomplete"
        placeholder="请输入院校名称"
        clearable
        @select="handleSelect"
      >
        <template #prefix>
          <img class="fdj" :src="fdj" alt="" />
        </template>
        <template #default="{ item }">
          <div
            class="option-item"
            v-html="formateText(item.dataName)"
            v-if="item.dataName"
          ></div>
        </template>
      </el-autocomplete>
      <el-button class="search-college" @click="jumpToSearchCollege"
        >查院校</el-button
      >
    </div>
    <el-button
      v-if="showExtraBtn"
      class="college-category"
      @click="jumpToSearchCollegeOnly"
      >院校大全</el-button
    >
  </div>
  <div class="history" v-if="props.showHistory">
    <img v-if="searchHistoryList.length > 0" class="icon" :src="clock" alt="" />
    <span v-if="searchHistoryList.length > 0" class="title">搜索历史</span>
    <div
      class="search-item-container"
      v-for="(item, index) in searchHistoryList.slice().reverse()"
      :key="index"
    >
      <div class="search-item" @click="gotoSchoolDetail(item)">
        {{ item.dataName }}
      </div>
      <img class="close" :src="close" alt="" @click="deleteHistory(item)" />
    </div>
  </div>
</template>

<script setup>
import { ElMessage } from 'element-plus';
import fdj from '@/assets/images/fdj.png';
import clock from '@/assets/images/clock.png';
import close from '@/assets/images/close.png';
import antiShake from '@/utils/antiShake.js';
import { matchMajorAndPositionList } from '@/api/collegeSearch';

import { ref, onMounted, onBeforeUnmount, onUnmounted, watch } from 'vue';
import { useRoute, useRouter } from 'vue-router'; // 导入路由
const router = useRouter();
const route = useRoute();

const inputData = ref('');
const searchResult = ref([]);
const props = defineProps({
  showHistory: {
    type: Boolean,
    default: () => false,
  },
  matchName: {
    type: String,
    default: () => '',
  },
  showExtraBtn: {
    type: Boolean,
    default: () => false,
  },
});
const emit = defineEmits(['updateData', 'upDateMatchName']);
const createFilter = (queryString) => {
  return (restaurant) => {
    if (restaurant.dataName) {
      return (
        restaurant.dataName.toLowerCase().indexOf(queryString.toLowerCase()) ===
        0
      );
    }
    return false;
  };
};

const querySearch = antiShake(async (queryString, cb) => {
  if (!inputData.value) {
    searchResult.value = [{ dataName: '输入院校进行搜索' }];
    cb([{ dataName: '输入院校进行搜索' }]);
  } else {
    matchMajorAndPositionList({
      searchTypeList: ['4'],
      matchName: inputData.value,
      pageSize: 30,
    }).then((res) => {
      if (res.code == 200) {
        searchResult.value = res.data;
        const results = searchResult.value;
        cb(results);
      }
    });
  }
}, 300);

const handleSelect = (item) => {
  if (item.dataName == '输入院校进行搜索') {
    return;
  } else {
    // 检查 searchHistoryList 中是否已存在当前对象
    const existingItem = searchHistoryList.value.find(
      (historyItem) => historyItem.dataId === item.dataId
    );
    if (!existingItem) {
      searchHistoryList.value.push(item);
      // 如果列表长度超过 10 条，删除最早的记录
      if (searchHistoryList.value.length > 9) {
        searchHistoryList.value.shift();
      }
    }
    gotoSchoolDetail(item);
    emit('updateData');
  }
};
const formateText = (content) => {
  if (content && content != '') {
    let text = inputData.value;
    let regStr = `(${text})`;
    let reg = new RegExp(regStr, 'g');
    // 正则替换，关键词飘红
    return content.replace(
      reg,
      '<span style="color:#0b6eff;">' + text + '</span>'
    );
  }
};

const searchHistoryList = ref([]);

const gotoSchoolDetail = (item) => {
  const currentRouteName = route.name;
  const routeObj = {
    name: 'SchoolDetail',
    query: {
      dataId: item.dataId,
      dataName: item.dataName,
    },
  };
  if (currentRouteName == 'SchoolDetail') {
    console.log('当前路径参数:', route.name);
    if (route.name == 'SchoolDetail') {
      localStorage.setItem('isSchoolDetail', '1'); // 这里是为了判断是否需要go(-1)
    }
    router.replace(routeObj);
  } else {
    router.push(routeObj);
  }
};
const jumpToSearchCollege = () => {
  if (route.name == 'SearchCollege') {
    emit('upDateMatchName', inputData.value); // 触发父组件的 updateData 事件
  } else {
    router.push({
      name: 'SearchCollege',
      query: {
        matchName: inputData.value || '',
      },
    });
  }
};
const jumpToSearchCollegeOnly = () => {
  router.push({
    name: 'SearchCollege',
    query: {},
  });
};
const deleteHistory = (item) => {
  const index = searchHistoryList.value.indexOf(item);
  if (index !== -1) {
    searchHistoryList.value.splice(index, 1);
  }
};
watch(
  () => props.matchName, // 监听 props.matchName 的变化
  (newMatchName) => {
    inputData.value = newMatchName; // 更新 inputData 的值为新的 matchName
  },
  { deep: true }
);
onMounted(() => {
  searchHistoryList.value =
    JSON.parse(localStorage.getItem('collegeHistory')) || [];
  inputData.value = props.matchName; // 初始化 inputData 的值为 props.matchName
});
onUnmounted(() => {
  localStorage.setItem(
    'collegeHistory',
    JSON.stringify(searchHistoryList.value)
  );
});
</script>

<style lang="scss" scoped>
.search-box-container {
  display: flex;
  justify-content: center;
  gap: 16px;
}
.search-box {
  // margin: 0 auto;
  display: flex;
  align-items: center;
  // position: relative;
  width: 1103px;
  height: 72px;
  box-sizing: border-box;
  background: #ffffff;
  border-radius: 15px;
  // 修改这里的边框样式
  border: 2px solid transparent;
  background-image: linear-gradient(white, white),
    linear-gradient(180deg, rgba(255, 255, 255, 1), rgba(206, 231, 245, 1));
  background-origin: border-box;
  background-clip: padding-box, border-box;
  // 移除原来的 border-image
  backdrop-filter: blur(24px);
  :deep(.el-autocomplete) {
    height: 100%;
    .el-input {
      height: 100%;
      .el-input__wrapper {
        border-radius: 12px;
        height: 100%;
        box-shadow: none;
        background-color: transparent;
        .el-input__inner {
          height: 100%;
          font-family: PingFangSC, PingFang SC;
          font-weight: 400;
          font-size: 22px;
          color: #333333;
        }
      }
      .el-input__wrapper:hover {
        box-shadow: none;
      }
    }
  }
  .search-college {
    cursor: pointer;
    // position: absolute;
    // right: 0;
    box-sizing: border-box;
    width: 176px;
    height: 72px;
    background: #0b6eff;
    border-radius: 12px;
    border: 3px solid #0b6eff;
    display: flex;
    align-items: center;
    justify-content: center;
    font-family: PingFang-SC, PingFang-SC;
    font-weight: bold;
    font-size: 26px;
    color: #ffffff;
  }

  .fdj {
    width: 24px;
    height: 24px;
    margin: 0 14px 0 23px;
  }
  .option-item {
    height: 60px;
  }
}
.college-category {
  cursor: pointer;
  width: 176px;
  height: 72px;
  background: #ff7d2d;
  border-radius: 12px;
  display: flex;
  align-items: center;
  justify-content: center;
  font-family: PingFang-SC, PingFang-SC;
  font-weight: bold;
  font-size: 24px;
  color: #ffffff;
}
.history {
  width: 55%;
  height: 132px;
  overflow: hidden;
  margin: 30px auto 0;
  display: flex;
  align-items: center;
  flex-wrap: wrap;
  .icon {
    width: 24px;
    height: 24px;
    margin-bottom: 12px;
  }
  .title {
    font-family: PingFangSC, PingFang SC;
    font-weight: 400;
    font-size: 22px;
    color: #0b6eff;
    margin: 0 12px 12px 10px;
    padding: 12px;
  }
  .search-item-container {
    display: flex;
    align-items: center;
    margin-right: 12px;
    margin-bottom: 12px;
    .search-item {
      border-radius: 4px;
      border: 1px solid #0b6eff;
      font-family: PingFangSC, PingFang SC;
      font-weight: 400;
      font-size: 22px;
      color: #0b6eff;
      padding: 12px;
      margin-right: 12px;
    }
    .close {
      width: 20px;
      height: 20px;
    }
  }
}

// 通过 my-autocomplete 类名设置下拉项高度
.my-autocomplete .option-item {
  height: 80px; // 可根据实际需求调整高度
  display: flex;
  align-items: center;
  font-size: 24px;
}
</style>
